// miniprogram/pages/blog/blog.js
let keyword = ''; //搜索关键字
Page({
  /**
   * 页面的初始数据
   */
  data: {
    modalShow: false,
    blogList: []
  },
  /**
   * 资源发布
   */
  publishFn() {
    // 判断用户是否授权
    wx.getSetting({
      success: (res) => {
        //授权成功
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: (res) => {
              const event = {
                detail: res.userInfo
              }
              this.loginsuccess(event)
            }
          })
        } else { //弹出底部弹出层
          this.setData({
            modalShow: true
          })
        }
        console.log(res)
      }
    })
  },
  /**
   * 登录成功
   */
  loginsuccess(userInfo) {
    const event = userInfo.detail;
    wx.navigateTo({
      url: `../blog-edit/blog-edit?nickName=${event.nickName}&avatarUrl=${event.avatarUrl}`,
    })
  },
  /**
   * 登录失败
   */
  loginfail() {
    wx.showModal({
      title: '授权用户才可以发布博客',
      content: '',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    /**
     * 调用云方法
     */
    // this.loadBlogList() 
    /**
     * 调用云数据库
     */
    const db = wx.cloud.database();
    db.collection('blog').orderBy('createTime', 'desc').get().then(res => {
      const data = res.data;
      for (let i = 0, len = data.length; i < len; i++) {
        data[i].createTime = data[i].createTime.toString()
      }
      this.setData({
        blogList: data
      })
    })
  },
  loadBlogList(start = 0) {
    console.log('更新中')
    wx.showLoading({
      title: '拼命加载中。。。。',
    })
    wx.cloud.callFunction({
      name: 'blog',
      data: {
        $url: 'list',
        start,
        keyword,
        count: 10,
      }
    }).then(res => {
      this.setData({
        blogList: this.data.blogList.concat(res.result)
      })
      wx.hideLoading();
      wx.stopPullDownRefresh();
      console.log(res)
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.loadBlogList(this.data.blogList.length)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      blogList: []
    })
    this.loadBlogList()
  },
  //搜索
  onSearch(event) {
    keyword = event.detail.keyword
    this.setData({
      blogList: []
    })
    this.loadBlogList()
  },
  goComment(event) {

    wx.navigateTo({
      url: '../blog-comment/blog-comment?blogId=' + event.target.dataset.blogid,
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(event) {
    let blogObj = event.target.dataset.blog;
    return {
      title: blogObj.content, // 标题
      path: `/pages/blog-comment/blog-comment?blogId=${blogObj._id}`, //点击的样式
      // imageUrl:'' // 分享的图片
    }
  }
})